package com.kyzh.core.download.down

import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.annotation.RequiresApi
import com.blankj.utilcode.util.AppUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.gushenge.core.beans.DownTaskBean
import com.jeremyliao.liveeventbus.LiveEventBus
import com.kyzh.core.R
import com.gushenge.core.base.activity.BaseActivity
import com.gushenge.core.beans.Game
import com.gushenge.core.dao.MMKVConsts
import com.gushenge.core.toast
import com.kyzh.core.MyApplication
import com.kyzh.core.databinding.ItemDownloadManagerBinding
import com.kyzh.core.utils.appInstall
import com.kyzh.core.utils.loadImage
import com.kyzh.core.utils.setVisibility
import com.liulishuo.okdownload.StatusUtil
import kotlinx.android.synthetic.main.activity_download_all.*
import org.litepal.LitePal
import org.litepal.extension.findAll
import java.io.File
import java.math.BigDecimal
import java.text.DecimalFormat

/**
 * 下载管理界面
 */
class DownActivity : BaseActivity() {

    private lateinit var adapter: DownAdapter
    private var downList = arrayListOf<DownTaskBean>()

    @RequiresApi(Build.VERSION_CODES.N)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_download_all)
        adapter = DownAdapter()
        recyclerView.adapter = adapter
    }

    override fun onResume() {
        super.onResume()
        setData()

    }
    fun setData() {
        downList.clear()
        val all = LitePal.findAll<DownTaskBean>()
        downList.addAll(all)
        LiveEventBus.get<Map<String, DownTaskBean>>("GAMETASK").observe(this) { data ->
            Log.e("TAG", "setData: " + data.size)
            downList.forEachIndexed { index, downTaskBean ->
                data[downTaskBean.url]?.apply {
                    if (this.url == downTaskBean.url) {
                        if(this.state==4){
                            downList.removeAt(index)
                        }else{
                            downList[index].state = this.state
                            downList[index].process = this.process
                        }
                        adapter.notifyDataSetChanged()
                    }
                }
            }
        }
        adapter.notifyDataSetChanged()
        Log.e("TAG", "setData: " + all.size)
        LiveEventBus.get<String>("GAMETASKREMOVE").observe(this){url->

        }


    }

    inner class DownAdapter :
        BaseQuickAdapter<DownTaskBean, BaseDataBindingHolder<ItemDownloadManagerBinding>>(
            R.layout.item_download_manager,
            downList
        ) {


        /**
         * 保留兩位小鼠
         */
        fun save2(progress: Float): Float {
            var bd = BigDecimal(progress.toString())
            bd = bd.setScale(2, 4);
            return bd.toFloat();
        }


        fun readableFileSize(size: Long): String? {
            if (size <= 0) return "0"
            val units = arrayOf("B", "KB", "MB", "GB", "TB")
            val digitGroups = (Math.log10(size.toDouble()) / Math.log10(1024.0)).toInt()
            return DecimalFormat("#,##0.#").format(size / Math.pow(1024.0, digitGroups.toDouble()))
                .toString() + " " + units[digitGroups]
        }

        override fun convert(
            holder: BaseDataBindingHolder<ItemDownloadManagerBinding>,
            item: DownTaskBean
        ) {
            holder.dataBinding?.apply {
                name.text = item.name
                if (item.icon.isNullOrBlank()) {

                    icon.setImageResource(R.drawable.logo_new)

                } else {
                    icon.loadImage(item.icon)
                }



                Log.e(
                    "TAG",
                    "convert: " + DownTask.getTaskByUrl(item.url)?.let { StatusUtil.getStatus(it) })

//
                pbProgress.progress = item.process.toInt()
                remove.setOnClickListener {
                    //先判断是否运行
                    if (DownTask.checkStatus(item) != 2) {
                        downList.remove(item)
                        item.delete()
                        DownTask.delect(item)
                        notifyDataSetChanged()
                    } else {
                        DownTask.delect(item)
                    }

                }
                val file = File(MMKVConsts.downloadDir + "/" + item.name + ".apk")

                kotlin.runCatching {
                    if (!item.size.isNullOrBlank()) {
                        if (item.size.contains("M")) {
                            downloadSize.setVisibility(false)
                        } else {
                            val fl =
                                (item.size.toFloat()) * item.process.toFloat() / 100
                            downloadSize.text = "${save2(fl)}M/${item.size}M"
                        }

                    } else {
                        downloadSize.setVisibility(false)
                    }
                }

                Log.e("TAG", "convert: " + file)
                //0 准备  1 下载 2 队列  3 完成  4删除
                val sqlList = LitePal.where("url = ?", item.url).findFirst(DownTaskBean::class.java)

                if (DownTask.getTaskByUrl(item.url) != null) {
                    val taskByUrl = DownTask.getTaskByUrl(item.url)
                    if (taskByUrl != null) {
                        val status = StatusUtil.getStatus(taskByUrl)
                        when (status) {
                            StatusUtil.Status.IDLE -> {
                                kotlin.runCatching {
                                    if(AppUtils.isAppInstalled(item.packageName)){
                                        start.text = "打开"
                                        netSpeed.text = "已下载"
                                    }else{
                                        start.text = "下载"
                                        netSpeed.text = "停止"
                                    }
                                }.onFailure {
                                    start.text = "下载"
                                    netSpeed.text = "停止"
                                }
                            }
                            StatusUtil.Status.RUNNING -> {
                                start.text = "暂停"
                                netSpeed.text = "下载中"
                            }
                            StatusUtil.Status.PENDING -> {
                                start.text = "排队"
                                netSpeed.text = "排队中"
                            }
                            StatusUtil.Status.COMPLETED -> {
                                kotlin.runCatching {
                                    if(AppUtils.isAppInstalled(item.packageName)){
                                        start.text = "打开"
                                        netSpeed.text = "已下载"
                                    }else{
                                        start.text = "安装"
                                        netSpeed.text = "下载完成"
                                    }
                                }.onFailure {
                                    start.text = "安装"
                                    netSpeed.text = "下载完成"
                                }

                            }
                            else -> {
                                when (sqlList.state) {
                                    3 -> {
                                        if (file.exists()) {
                                            start.text = "安装"
                                            netSpeed.text = "下载完成"
                                        } else {
                                            start.text = "重新下载"
                                            netSpeed.text = "已删除"
                                        }
                                    }
                                    else -> {
                                        start.text = "下载"
                                        netSpeed.text = "停止"
                                    }
                                }
                            }
                        }
                    }
                } else {
                    when (sqlList.state) {
                        3 -> {
                            if (file.exists()) {
                                kotlin.runCatching {
                                    if(AppUtils.isAppInstalled(item.packageName)){
                                        start.text = "打开"
                                        netSpeed.text = "已下载"
                                    }else{
                                        start.text = "安装"
                                        netSpeed.text = "下载完成"
                                    }
                                }.onFailure {
                                    start.text = "安装"
                                    netSpeed.text = "下载完成"
                                }
                            } else {
                                start.text = "重新下载"
                                netSpeed.text = "已删除"
                            }
                        }
                        else -> {
                            start.text = "下载"
                            netSpeed.text = "停止"
                        }
                    }
                }


//                val checkStatus = DownTask.checkStatus(item)
//                if (checkStatus == 2) {
//                    start.text = "暂停"
//                } else if (checkStatus == 1) {
//                    start.text = "安装"
//                }
                start.setOnClickListener {
                    when (start.text) {
                        "安装" -> {
                            MyApplication.instance.appInstall(file.absolutePath,item.url)
                        }
                        "打开" -> {
                            kotlin.runCatching {
                                AppUtils.launchApp(item.packageName)
                            }.onFailure {
                                "打开失败，请手动打开".toast()
                            }
                        }
                        else -> {
                            DownTask.downLoad(item)
                        }
                    }
                }
            }

        }
    }
}